//
//  ChooseAddressViewController.m
//  HuaRun2
//
//  Created by admin on 2017/11/5.
//  Copyright © 2017年 Sunny. All rights reserved.
//

#import "ChooseAddressViewController.h"
#import "ChooseRelatedAddressCell.h"
#import "AddAddressCell.h"
#import "ChooseCountryViewController.h"
#import "ConditionModel.h"
#import "AddressModel.h"

@interface ChooseAddressViewController ()
@property(nonatomic, strong)ConditionModel * model;
@end

@implementation ChooseAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;

    [self viewInit];
    [self dataInit];
    [self methodBind];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewInit {

    self.navigationItem.title = NSLocalizedString(@"ChooseAddress",nil);
    [self.tableView registerClass:[ChooseRelatedAddressCell class] forCellReuseIdentifier:@"BaseInsetTableViewCell"];
    [self.tableView registerClass:[AddAddressCell class] forCellReuseIdentifier:@"AddAddressCell"];
    
    self.tableView.estimatedRowHeight = 213;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:self action:@selector(backMethod)];
    self.navigationItem.backBarButtonItem = backItem;
    
}

- (void)methodBind {
    
    weakself(ws);

    [self nbRightImageName:@"save" title:nil taget:self clickBlock:^(id result) {
        [ws submitMethod];
    }];
    
    if (!_isFromEditContact) {
        [self fetchAllAddressList];
    }else {
        [self fetchRelatedAddressList];
    }
}

- (void)dataInit {
    
    self.current = 1;
    self.size = 10;
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }
    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        AddAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AddAddressCell"                                
                                                               forIndexPath:indexPath];
        
        __weak AddAddressCell * wcell = cell;
        
        weakself(ws);
        [cell.guoJiaBgView addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
            
            ChooseCountryViewController * countryVC = [ChooseCountryViewController new];
            countryVC.clickBlock = ^(id result) {
                
                ConditionModel * model = result;
                wcell.guoJiaValLab.text = [NSString stringWithFormat:@"%@%@",
                                            model.value, model.valueCinese];
                [tableView reloadData];
                ws.model = model;
            };
            [ws.navigationController pushViewController:countryVC animated:YES];
            
        }];
        
        return cell;

    }
    ChooseRelatedAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BaseInsetTableViewCell"
                                                                   forIndexPath:indexPath];
    
    AddressModel * addressModel = self.dataArray[indexPath.row];
    cell.addressModel = addressModel;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 1) {
        AddressModel * addressModel3 = self.dataArray[indexPath.row];
        addressModel3.isSelected = !addressModel3.isSelected;
        [tableView reloadData];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        
        return [self makeCommonSectionHeaderViewWithText:NSLocalizedString(@"newAddress", nil)];
        
    }else if (section ==1) {
        
        return [self makeCommonSectionHeaderViewWithText:NSLocalizedString(@"guanLianAddress", nil)];
    }
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 44;
}

#pragma mark method

//返回上个页面
- (void)backMethod {
    [self.navigationController popViewControllerAnimated:YES];
}

//获取公司下所有地址
- (void)fetchAllAddressList {
    NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl,
                      kCompanyDetailAddressListUrl];
    NSString * accountId = _accountId ? _accountId : @"";
    NSDictionary * dic = @{@"accountId": accountId,
                           @"isPrivate ": @(0)};
    
    weakself(ws);
    [NetWorkHelper getWithURLString:url parameters:dic success:^(id object) {
        if (![object[@"code"] isEqual: kSuccessCode]) {
            NSString * info = [NSString isemptyStr:object[@"msg"]] ? kUnknownError : object[@"msg"];
            [ws showWithText:info];
            return;
        }
        NSArray * addressArray = [NSArray yy_modelArrayWithClass:[AddressModel class]
                                                            json:object[@"list"]];

        ws.dataArray = addressArray;
        [ws.tableView reloadData];
        
    } failure:^(NSError *error) {
        [ws showWithText:kNetworkError];
    }];
    
}

//获取联系人、公司的所有地址
- (void) fetchRelatedAddressList {
    NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl,
                      kContact_Edit_Address_Url];
    
    weakself(ws);
    NSDictionary * dic = @{@"current": @(self.current),
                           @"size": @(self.size),
                           @"accountId": _accountId ? _accountId : @"",
                           @"contactId": _contactId ? _contactId : @""};
    [NetWorkHelper getWithURLString:url parameters:dic success:^(id object) {
        if (![object[@"code"] isEqual: kSuccessCode]) {
            [ws showWithText:[NSString showStringWithStr:object[@"msg"]]];
            return;
        }
        NSArray * array = [NSArray yy_modelArrayWithClass:[AddressModel class] json:object[@"list"]];
        
        ws.dataArray = array;
        [ws.tableView reloadData];
        
    } failure:^(NSError *error) {
        [ws showWithText:kNetworkError];
    }];
}

//完成方法
- (void)submitMethod {
    [self.view endEditing:YES];
    
    NSMutableString * mutAddStr = [NSMutableString stringWithCapacity:1];
    NSMutableString * mutCancelStr = [NSMutableString stringWithCapacity:1];

    NSMutableString * mutAddNameStr = [NSMutableString stringWithCapacity:1];

    for (int i = 0; i < _dataArray.count; i++) {
        AddressModel * addressModel1 = self.dataArray[i];
        BOOL isSelectedStatus = ![NSString isemptyStr:addressModel1.contactId];
        NSLog(@"%d + %@ %d", addressModel1.isSelected , addressModel1.contactId
              , isSelectedStatus);
        
        if (isSelectedStatus != addressModel1.isSelected) {
            //取消关联
            if (isSelectedStatus && !addressModel1.isSelected) {
                [mutCancelStr appendFormat:@"%@,", addressModel1.id];
            }
            //添加关联
            if (!isSelectedStatus && addressModel1.isSelected) {
                [mutAddStr appendFormat:@"%@,", addressModel1.id];
                [mutAddNameStr appendFormat:@"%@,", addressModel1.name];
            }
        }
    }
    if (mutAddNameStr.length > 1) {
        [mutAddNameStr replaceCharactersInRange:NSMakeRange(mutAddNameStr.length - 1, 1) withString:@""];
    }
    
    if (mutAddStr.length > 1) {
        [mutAddStr replaceCharactersInRange:NSMakeRange(mutAddStr.length - 1, 1) withString:@""];
    }
    
    if (mutCancelStr.length > 1) {
        [mutCancelStr replaceCharactersInRange:NSMakeRange(mutCancelStr.length - 1, 1) withString:@""];
    }
    if (mutCancelStr.length == 0 && mutAddStr.length == 0) {

        [self addAddressMethod];
    }else {
        if (_isFromEditContact) {
            
            [self relateAddressWithCancelStr:mutCancelStr
                                      addStr:mutAddStr
                                  addNameStr:mutAddNameStr];
        }else {
            self.clickBlock ? self.clickBlock(mutAddStr, mutAddNameStr) : nil;
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}


//关联地址
- (void)relateAddressWithCancelStr:(NSString *)cancelStr
                            addStr:(NSString *)addStr
                        addNameStr:(NSString *)addNameStr {
    NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl,
                      kContact_batchProcessAddress_Url];
    
    weakself(ws);
    NSDictionary * dic = @{@"cancelAddressIds": cancelStr,
                           @"addAddressIds": addStr,
                           @"contactId":  _contactId ? _contactId : @""};
    [NetWorkHelper postWithURLString:url parameters:dic success:^(id object) {
        if (![object[@"code"] isEqual: kSuccessCode]) {
            [ws showWithText:[NSString showStringWithStr:object[@"msg"]]];
            return;
        }
        ws.clickBlock ? ws.clickBlock(addStr, addNameStr) : nil;
        [ws.navigationController popViewControllerAnimated:YES];

    } failure:^(NSError *error) {
        [ws showWithText:kNetworkError];
    }];
}

//增加地址
- (void)addAddressMethod {
    NSString * url = [NSString stringWithFormat:@"%@%@", kBaseUrl,
                      kContact_add_Address_Url];
    weakself(ws);
    AddAddressCell * cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    if (cell.nameTF.text.length == 0) {
        [self showAlert:NSLocalizedString(@"chooseOrAddAddress", nil)];
        return;
    }
    
    NSString * englishText = [NSString showStringWithStr: cell.englishTF.text];
    NSString * chineseText = [NSString showStringWithStr: cell.chineseTF.text];
    NSString * emailText   = [NSString showStringWithStr: cell.emailTF.text ];
    NSString * nameText   = [NSString showStringWithStr: cell.nameTF.text ];
    
    NSDictionary * dic = @{@"email": emailText,
                           @"address1Chinese": chineseText,
                           @"address1English": englishText,
                           @"name": nameText ? nameText : @"",
                           @"isPrivate": @(0),
                           @"company": _accountId ? _accountId : @"",
                           @"contactId": _contactId ? _contactId : @"",
                           @"countryEnglish":_model.value?_model.value : @"",
                           @"countryChinese": _model.valueCinese ?_model.valueCinese: @"" };
    
    [NetWorkHelper postWithURLString:url parameters:dic success:^(id object) {
        if (![object[@"code"] isEqual: kSuccessCode]) {
            [ws showWithText:[NSString showStringWithStr:object[@"msg"]]];
            return;
        }
        [self showAlert:NSLocalizedString(@"create_success", nil)];

    } failure:^(NSError *error) {
        [ws showWithText:kNetworkError];
    }];
}
//创建头部视图
- (UIView *)makeCommonSectionHeaderViewWithText:(NSString *)text{
    
    UIView * view = [[UIView alloc] initWithFrame:(CGRectMake(0, 0, kMainScreenWidth, 50))];
    view.backgroundColor = RGBA(249, 249, 249, 1);
    
    UILabel * label = [[UILabel alloc] init];
    label.font = kFontSize15;
    label.text = text;
    label.textColor = [UIColor colorWithHex:@"3c3c3c"];
    [view addSubview:label];
    
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(view).offset(kMargin10);
        make.centerY.mas_equalTo(view);
        make.size.mas_equalTo(CGSizeMake(150, 20));
    }];
    return view;
    
}


-(void)nbRightImageName:(NSString *)leftImgName title:(NSString *)atitle taget:(UIViewController *)ctrl clickBlock:(void (^)(id))btnClick{
    
    UIImage *img = [UIImage imageNamed:leftImgName];
    
    UIButton *btnLeftNew = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnLeftNew setFrame:CGRectMake(0, 0, 50, 50)];
    [btnLeftNew setBackgroundColor:[UIColor  clearColor]];
    [btnLeftNew addTarget:self action:@selector(customRightEventBlock:) forControlEvents:UIControlEventTouchUpInside];
    if (leftImgName != nil) {
        
        [btnLeftNew setImage:img forState:UIControlStateNormal];
    }
    
    [btnLeftNew setTitle:atitle forState:UIControlStateNormal];
    [btnLeftNew setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    
    btnLeftNew.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -10);
    btnLeftNew.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -10);
    btnLeftNew.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -10);
    
    btnLeftNew.titleLabel.font = [UIFont systemFontOfSize:14];
    
    ctrl.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btnLeftNew];
    
    self.xhRightBtnClickBlock = btnClick;

}

- (void)customRightEventBlock:(UIButton *)sender{
    
    NSLog(@"右边点击");
    if (self.xhRightBtnClickBlock) {
        
        self.xhRightBtnClickBlock(sender);
        
    }
    
    
}

@end
